package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.content.mapper.CourseMarketMapper;
import com.xuecheng.content.model.po.CourseMarket;
import com.xuecheng.content.service.CourseMarketService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Collection;

/**
 * <p>
 * 课程营销信息 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class CourseMarketServiceImpl extends ServiceImpl<CourseMarketMapper, CourseMarket> implements CourseMarketService {

  @Override
  public int save2(CourseMarket courseMarket) {
    //参数的合法性校验
    String charge = courseMarket.getCharge();
    if (StringUtils.isEmpty(charge)) {
      throw new RuntimeException("收费规则为空");
    }
    //如果课程收费，价格没有填写也需要抛出异常
    if (charge.equals("201001")) {
      if (courseMarket.getPrice() == null || courseMarket.getPrice() <= 0) {
        throw new RuntimeException("课程的价格不能为空并且必须大于0");
//        XueChengPlusException.cast("课程的价格不能为空并且必须大于0");
      }
    }

    //从数据库查询营销信息,存在则更新，不存在则添加
    Long id = courseMarket.getId();//主键
    CourseMarket courseMarketDB = baseMapper.selectById(id);
    if (courseMarketDB == null) {
      //插入数据库
      return baseMapper.insert(courseMarket);
    } else {
      //将courseMarketNew拷贝到courseMarket
      BeanUtils.copyProperties(courseMarket, courseMarketDB);
      courseMarketDB.setId(courseMarket.getId());
      //更新
      return baseMapper.updateById(courseMarketDB);
    }
  }
}
